
import pymongo
from pymongo import MongoClient
import json

class StockAnalyse:

    def __init__(self, host="localhost"):
        self.client_v = MongoClient(host)
        self.db_v = self.client_v["stock"]

    def coll_value_f(self, coll):
        self.coll_v = self.db_v[coll]
        coll_value_t = self.coll_v.find().count()
        if coll_value_t == 0:
            print("This collections is not exist or no data")
            return None
        else:
            return self.coll_v

class StockAnalyseBefore(StockAnalyse):
    def __init__(self, coll_name):
        super(StockAnalyseBefore, self).__init__()
        self.coll_v = self.coll_value_f(coll_name)
        if self.coll_v == None:
            return None

    indus_all = []

    ## each concepts how many stocks there of topbefore some days
    def __indus_ana(self, name):
        index = 0
        if len(self.indus_all) == 0:
            item = {}
            item["name"] = name
            item["count"] = 1
            self.indus_all.append(item)

        find = False
        for item in self.indus_all:
            if item["name"] == name:
                self.indus_all[index]["count"] = self.indus_all[index]["count"] + 1
                find = True
                break
            index = index + 1

        if find == False:
            item = {}
            item["name"] = name
            item["count"] = 1
            self.indus_all.append(item)

    def debug_indus(self):
        print("debug out put industry")
        for item in self.indus_all:
            print("item name: ", item["name"], " - count: ", item["count"])

    def analyse(self):
        for item in self.coll_v.find().sort("count", pymongo.DESCENDING):
            # print(item["name"], "-", item["count"])
            for indus in self.db_v.industry.find({"name":item["name"]}):
               if indus != None:
                    self.__indus_ana(indus["c_name"])

## Analyse how many industry and areas for all stocks.
class StockAnalyseBase(StockAnalyse):
    def __init__(self):
        print("init here....")
        super(StockAnalyseBase, self).__init__()

    def _industry_counts(self, lists):
        return self._counts(lists, "industry")

    def _area_counts(self, lists):
        return self._counts(lists, "area")

    def _counts(self, lists, name):
        _need = []
        for i in lists:
            if len(_need) == 0:
                item = {}
                item[name] = i[name]
                item["counts"] = 0
                _need.append(item)
            find = False
            for j in _need:
                if j[name] == i[name]:
                    j["counts"] = j["counts"] + 1
                    find = True
                    break
            if find == False:
                item = {}
                item[name] = i[name]
                item["counts"] = 0
                _need.append(item)

        _need_new = []
        for i in _need:
            nitem = (i[name], i["counts"])
            _need_new.append(nitem)
        _need_sorted = sorted(_need_new, key=lambda x: x[1], reverse=True)
        return _need_sorted

    def data_print(self, name):
        if name == "industry":
            for i in self.industry_sorted:
                print("industry: ", i[0], ", counts: ", i[1])
        elif name == "area":
            for i in self.area_sorted:
                print("area: ", i[0], ", counts: ", i[1])

    def address(self, coll_v):
        self.coll_v = self.coll_value_f(coll_v)
        v = self.coll_v.find()
        v_need = []
        for i in v:
            item = {}
            item["name"] = i["name"]
            item["industry"] = i["industry"]
            item["area"] = i["area"]
            v_need.append(item)
        self.area_sorted = self._area_counts(v_need)
        self.industry_sorted = self._industry_counts(v_need)

class StockAnalyseToday(StockAnalyse):

    def loaddata(self, date):
        col_name = "alltoday_" + date
        print("Load data of ", col_name)
        self.data = self.coll_value_f(col_name)

    def sort_percent(self, ifreverse=True):
        return sorted(self.data, key=lambda x: x[1], reverse=True)

    def statistics(self):
        for per in self.data:
            if int(per["changepercent"]) > 7:
                self.sevitems.append(per)
        return self.sevitems;

class StockAnalyseCompany():
    def load_data(self, file):
        print("load data from file ", file)
        with open(file, "r") as f:
            data = f.read()
            self.data_json = json.loads(data)
            f.close()
        
    def parse(self):
        self.areas = []
        for v in self.data_json:
            tarea = v["area"]
            if len(self.areas) == 0:
                item = {}
                item["area"] = tarea
                item["count"] = 1
                self.areas.append(item)
                continue

            find = False
            for k in self.areas:
                if k["area"] == tarea:
                    k["count"] = k["count"] + 1
                    find = True
            
            if not find:
                item = {}
                item["area"] = tarea
                item["count"] = 1
                self.areas.append(item)
    
    def out(self):
        print("len of areas : ", len(self.areas))
        self.areas = sorted(self.areas, key = lambda area : area["count"])
        for v in self.areas:
            print("area ", v["area"], " count ", v["count"])
